//
//  LMPartnerListViewController.m
//  LM
//
//  Created by Kien Tran on 2/4/13.
//  Copyright (c) 2013 Kien Tran. All rights reserved.
//

#import "LMPartnerListViewController.h"
#import "LMLocalAccountManager.h"
#import "LMLocalPartner.h"
#import "LMConstant.h"
#import "LMPartnerDetailViewController.h"

@interface LMPartnerListViewController () {
    __weak NSMutableArray *_partners;
    __weak LMLocalPartner *_selectedPartners;
}

@end

@implementation LMPartnerListViewController
@synthesize tableView = _tableView;


- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self setBackButton];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    _partners = [LMLocalAccountManager sharedPartnerArray];
    _selectedPartners = [LMLocalAccountManager sharedSelectedPartner];
    
    [self.tableView reloadData];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    } else {
        return _partners ? [_partners count] : 0;
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"Add action";
    } else {
        return @"Partner List";
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0){
        
       UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Add Action"];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"Add new partner.";
        
        
        return cell;

	}
	else {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (!cell) {
            // Configure the cell...
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        
        LMLocalPartner *localPartner = [_partners objectAtIndex:indexPath.row];
        cell.textLabel.text = localPartner.userName;
        cell.detailTextLabel.text = [LMGlobalHelper stringWithDate:localPartner.birthday];
        
        if (localPartner == _selectedPartners) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;

    }
 }

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
    
    // If user choose adding row and in editing mode
    if (indexPath.section == 1 && self.tableView.isEditing) {
        [self performSegueWithIdentifier:kPushToViewPartnerDetail sender:self];
    } else if (indexPath.section == 1 && !self.tableView.isEditing) {
        _selectedPartners = [LMLocalAccountManager setSelectedPartner:[_partners objectAtIndex:indexPath.row]];
        [self.tableView reloadData];
    }
    else {
        if ([LMLocalAccountManager canCreatePartner]) {
            [self performSegueWithIdentifier:kPushToAddPartner sender:self];
        } else {
            [[[UIAlertView alloc] initWithTitle:kAlertTitle message:kLimitPartnerAlert delegate:nil cancelButtonTitle:kAlertOK otherButtonTitles:nil, nil] show];
        }

        
    }

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [LMLocalAccountManager removePartnerWithIndex:indexPath.row];
        _selectedPartners = [LMLocalAccountManager sharedSelectedPartner];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
        [self.tableView reloadData];
    }
   
}

- (IBAction)touchDownEdit:(id)sender {
    [self setEditingTable:YES];
}

- (void)setEditingTable:(BOOL) editing {
    if (editing) {
        [self.navigationItem.rightBarButtonItem setAction:@selector(touchDownDone:)];
        [self.tableView setEditing:YES animated:YES];
        [self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];
        [self.tableView setAllowsSelectionDuringEditing:YES];
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];

    } else {
        [self.navigationItem.rightBarButtonItem setAction:@selector(touchDownEdit:)];
        [self.tableView setEditing:NO animated:YES];
        [self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStylePlain];
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
    }
}

- (void)backAction {
    [self dismissModalViewControllerAnimated:YES];
}
- (void)setBackButton {
    // create button
    UIButton* backButton = [UIButton buttonWithType:101]; // left-pointing shape!
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    
    // create button item -- possible because UIButton subclasses UIView!
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    // add to toolbar, or to a navbar (you should only have one of these!)

    [self.navigationItem setLeftBarButtonItem:backItem];
}

- (IBAction)touchDownDone:(id)sender {
    [self setEditingTable:NO];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:kPushToViewPartnerDetail]) {
        LMPartnerDetailViewController *detailController = [segue destinationViewController];
        detailController.localUser = [[_partners objectAtIndex:self.tableView.indexPathForSelectedRow.row] copy];
    } else if ([[segue identifier] isEqualToString:kPushToAddPartner]) {
        LMEditingLocalUserViewController *editingController = [segue destinationViewController];
        editingController.localUser = [[LMLocalPartner alloc] init];
    }
}
@end
